package cn.car91.activity;

import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.http.HttpHandler;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

public class UserForgetActivity extends BaseActivity {
    @ViewInject(R.id.user_phone)
    EditText phoneText;
    @ViewInject(R.id.user_code)
    EditText codeText;
    @ViewInject(R.id.user_password)
    EditText passwordText;
    @ViewInject(R.id.user_repassword)
    EditText repasswordText;

    @ViewInject(R.id.code_btn)
    Button codeBtn;
    @ViewInject(R.id.forget_next_btn)
    Button nextBtn;
    @ViewInject(R.id.forget_btn_now)
    Button forgetNowBtn;

    @ViewInject(R.id.forget_basic)
    View basicView;
    @ViewInject(R.id.forget_basic_info)
    View infoView;

    boolean phoneStatus = false;
    boolean codeStatus = false;
    boolean pwdStatus = false;
    boolean repwdStatus = false;

    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_forget);
        super.onCreate(savedInstanceState);

        phoneText.addTextChangedListener(onPhoneWatcher);
        codeText.addTextChangedListener(onCodeWatcher);
        codeBtn.setOnClickListener(onCodeClickListener);

        passwordText.addTextChangedListener(onPwdWatcher);
        repasswordText.addTextChangedListener(onRePwdWatcher);

        forgetNowBtn.setOnClickListener(onRegClickListener);

        nextBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (phoneStatus && codeStatus) {
                    basicView.setVisibility(View.GONE);
                    infoView.setVisibility(View.VISIBLE);
                } else {
                    infoView.setVisibility(View.GONE);
                    basicView.setVisibility(View.VISIBLE);
                }
            }
        });

        ((TextView) findViewById(R.id.header_text)).setText(R.string.forget_btn);
    }

    private void changeForgetBtn() {
        if (phoneStatus && codeStatus)
            nextBtn.setEnabled(true);
        else
            nextBtn.setEnabled(false);
    }

    private void changeForgetBtnNow() {
        if (phoneStatus && codeStatus && pwdStatus && repwdStatus)
            forgetNowBtn.setEnabled(true);
        else
            forgetNowBtn.setEnabled(false);
    }

    TextWatcher onPhoneWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            if (RegexUtil.isMobile(phoneText.getText().toString())) {
                Drawable drawable = getResources().getDrawable(R.drawable.error_ico);
                drawable.setBounds(0, 0, phoneText.getMeasuredHeight() / 3, phoneText.getMeasuredHeight() / 3);
                phoneText.setCompoundDrawables(null, null, drawable, null);
                phoneStatus = false;
                changeForgetBtn();
            }
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            if (RegexUtil.isMobile(phoneText.getText().toString())) {
                codeBtn.setEnabled(true);
                HttpHandler.httpHandler.checkUserAccountName(phoneText.getText().toString().trim(), callBack);
            } else {
                codeBtn.setEnabled(false);
            }
        }

        private RequestCallBack callBack = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {

            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                JSONObject jsonObject = JSON.parseObject(arg0.result.toString());
                String status = jsonObject.getString("status");

                Drawable drawable = getResources().getDrawable(R.drawable.error_ico);
                if (status.equals("n")) {
                    drawable = getResources().getDrawable(R.drawable.ok_ico);
                    phoneStatus = true;
                } else {
                    phoneStatus = false;
                }
                changeForgetBtn();
                drawable.setBounds(0, 0, phoneText.getMeasuredHeight() / 3, phoneText.getMeasuredHeight() / 3);
                phoneText.setCompoundDrawables(null, null, drawable, null);
            }
        };
    };

    TextWatcher onCodeWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            if (codeText.getText().length() >= 4) {
            	HttpHandler.httpHandler.checkUserAccountCode(codeText.getText().toString().trim(), callBack);
            } else {
                codeStatus = false;
                changeForgetBtn();
            }
        }

        private RequestCallBack callBack = new RequestCallBack() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {

            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                JSONObject jsonObject = JSON.parseObject(arg0.result.toString());
                String status = jsonObject.getString("status");
                Drawable drawable = getResources().getDrawable(R.drawable.error_ico);
                if (status.equals("y")) {
                    drawable = getResources().getDrawable(R.drawable.ok_ico);
                    codeStatus = true;
                } else {
                    codeStatus = false;
                }
                changeForgetBtn();
                drawable.setBounds(0, 0, codeText.getMeasuredHeight() / 3, codeText.getMeasuredHeight() / 3);
                codeText.setCompoundDrawables(null, null, drawable, null);
            }
        };
    };

    private TextWatcher onPwdWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String pwd = passwordText.getText().toString().trim();
            if (pwd.length() < 6 || pwd.length() > 18) {
                pwdStatus = false;
            } else {
                if (repwdStatus) {
                    if (pwd.equals(repasswordText.getText().toString()))
                        repwdStatus = true;
                    else
                        repwdStatus = false;
                } else {
                    if (pwd.equals(repasswordText.getText().toString()))
                        repwdStatus = true;
                    else
                        repwdStatus = false;

                    pwdStatus = true;
                }
            }
            changeForgetBtnNow();
        }
    };

    private TextWatcher onRePwdWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            String pwd = repasswordText.getText().toString().trim();
            if (pwd.length() < 6 || pwd.length() > 18) {
                repwdStatus = false;
            } else {
                if (pwd.equals(passwordText.getText().toString())) {
                    repwdStatus = true;
                } else {
                    repwdStatus = false;
                }
            }
            changeForgetBtnNow();
        }
    };

    private OnClickListener onCodeClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (RegexUtil.isMobile(phoneText.getText().toString())) {
            	HttpHandler.httpHandler.sendForgetCode(phoneText.getText().toString().trim(), callBack);
            } else {
                new HerilyAlertDialog.Builder(UserForgetActivity.this).setTitle("提示").setMessage("请输入正确的手机号").create().show();
            }
        }

        private RequestCallBack callBack = new RequestCallBack() {
            int second = 60;
            Handler handler = new Handler();
            Runnable updateThread = new Runnable() {
                public void run() {
                    if (second < 1) {
                        phoneText.setEnabled(true);
                        codeBtn.setText(R.string.reg_code_btn_re);
                        codeBtn.setEnabled(true);
                        second = 60;
                        handler.removeCallbacks(updateThread);
                    } else {
                        phoneText.setEnabled(false);
                        codeBtn.setText(second + "秒后重新发送");
                        second--;
                        handler.postDelayed(updateThread, 1000);
                    }
                }
            };

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                codeBtn.setEnabled(false);
                handler.post(updateThread);
                super.onStart();
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(UserForgetActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                codeBtn.setEnabled(true);
                handler.removeCallbacks(updateThread);
                codeBtn.setText(R.string.reg_code_btn);
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                String result = arg0.result.toString().trim();
                if (result.equals("no-mobile")) {
                    Toast.makeText(UserForgetActivity.this, "手机未注册", Toast.LENGTH_SHORT).show();
                    phoneText.requestFocus();
                    codeBtn.setEnabled(true);
                    handler.removeCallbacks(updateThread);
                    codeBtn.setText(R.string.reg_code_btn);
                } else if (result.equals("mobile-error")) {
                    Toast.makeText(UserForgetActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                    phoneText.requestFocus();
                    codeBtn.setEnabled(true);
                    handler.removeCallbacks(updateThread);
                    codeBtn.setText(R.string.reg_code_btn);
                } else if (result.equals("send-error")) {
                    Toast.makeText(UserForgetActivity.this, "验证码发送失败，请稍后重试", Toast.LENGTH_LONG).show();
                } else if (result.equals("send-ok")) {
                    codeText.requestFocus();
                } else {
                    Toast.makeText(UserForgetActivity.this, "服务器异常，工程师正在修复中", Toast.LENGTH_LONG).show();
                }
            }
        };
    };

    private OnClickListener onRegClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if (phoneStatus && codeStatus && pwdStatus && repwdStatus) {
                String pwd = passwordText.getText().toString();
                String rpwd = repasswordText.getText().toString();
                String mobileCode = codeText.getText().toString().trim();
                String mobile = phoneText.getText().toString().trim();

                HttpHandler.httpHandler.retrieveAccount(mobile, mobileCode, pwd, rpwd, callBack);
            } else {
                changeForgetBtnNow();
            }
        }

        private RequestCallBack callBack = new RequestCallBack() {

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                forgetNowBtn.setEnabled(false);
                super.onStart();
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub
                changeForgetBtnNow();
            }

            @Override
            public void onSuccess(ResponseInfo arg0) {
                // TODO Auto-generated method stub
                String result = arg0.result.toString();
                if (result.equals("code-error")) {
                    Toast.makeText(UserForgetActivity.this, "验证错误", Toast.LENGTH_SHORT).show();
                    codeText.requestFocus();
                    codeStatus = false;
                    changeForgetBtn();
                    infoView.setVisibility(View.GONE);
                    basicView.setVisibility(View.VISIBLE);
                } else if (result.equals("toforgot-error")) {
                    Toast.makeText(UserForgetActivity.this, "该手机未注册", Toast.LENGTH_SHORT).show();
                    phoneText.requestFocus();
                    phoneStatus = false;
                    changeForgetBtn();
                    infoView.setVisibility(View.GONE);
                    basicView.setVisibility(View.VISIBLE);
                } else if (result.equals("mobile-error")) {
                    Toast.makeText(UserForgetActivity.this, "手机错误", Toast.LENGTH_SHORT).show();
                    phoneText.requestFocus();
                    phoneStatus = false;
                    changeForgetBtn();
                    infoView.setVisibility(View.GONE);
                    basicView.setVisibility(View.VISIBLE);
                } else if (result.equals("password-error")) {
                    Toast.makeText(UserForgetActivity.this, "密码修改失败", Toast.LENGTH_SHORT).show();
                    passwordText.requestFocus();
                    pwdStatus = false;
                } else if (result.equals("forgot-success")) {
                    new HerilyAlertDialog.Builder(UserForgetActivity.this).setTitle("恭喜").setMessage("密码修改成功\n请牢记新密码")
                            .setNegativeButton("完成", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // TODO Auto-generated method stub
                                    finish();
                                }
                            }).create().show();
                } else {
                    new HerilyAlertDialog.Builder(UserForgetActivity.this).setTitle("提示").setMessage("服务器异常，工程师正在修复中").create().show();
                }
                changeForgetBtnNow();
            }
        };
    };
}
